library(shiny)
library(ggplot2)
library(ggthemes)
library(wesanderson)

source("./base.R")

ui <- fluidPage(
  titlePanel("Anayse Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("usedb", h4("Data From"),
                  choices = c("MongoDB",
                              "CSV"), 
                  selected = "MongoDB"),
      textInput("path", h4("Path of csv directory"), placeholder = "Only valid for CSV"),
      dateInput("date", h4("Choose Date"), value="2017-10-09"),
      sliderInput("scope", "Scope Limit", min = -11.0, max = 11.0, step = 0.1, value = c(8,11)),
      selectInput("concept", h4("Concept:"), 
                  choices = c("All", "None"),
                  selected = "None"),
      selectInput("area", h4("Area"),
                  choices = c("All", "None"),
                  selected = "None"),
      selectInput("industry", h4("industry"),
                  choices = c("All", "None"),
                  selected = "None")
    ),
    
    mainPanel(
      dataTableOutput("datalist")
    )
  )
)

server <- function(input, output, session) {
  old_concepts <- Nile
  old_industry <- Nile
  old_area <- Nile
  output$datalist <- renderDataTable({
    USEDB = TRUE
    csv_path = ""
    if (input$usedb == "CSV") {
      USEDB = FALSE
      csv_path = input$path
    }
    time_str <- gsub("-","", input$date)
    paste("You selected ", USEDB, ", time ", time_str)
    
    todaydata <- get_data_todayall(USEDB, "", time_str, path = csv_path)
    todaydata <- todayall_add_level(todaydata)
    
    companies <- get_data_companies(USEDB)
    concepts <- get_data_concepts(USEDB)
    
    hc_all <- take_out_companies(todaydata, companies, input$scope[2], input$scope[1])
    
    conceptlist <- get_all_concepts_from(concepts, hc_all)
    industrylist <- get_all_industry(hc_all)
    arealist <- get_all_area(hc_all)
    
    if (length(old_concepts) != length(conceptlist)) {
        updateSelectInput(session, "concept", choices = c("All", conceptlist))
        old_concepts <- conceptlist
    }
    if (length(old_area) != length(arealist)) {
      updateSelectInput(session, "area", choices = c("All", arealist))
      old_area <- arealist
    }
    if (length(old_industry) != length(industrylist)) {
      updateSelectInput(session, "industry", choices = c("All", industrylist))
      old_industry <- industrylist
    }
    
    hc_all <- get_data_filter(hc_all, concepts, input$concept, input$area, input$industry)
    hc_all
  })
}

shinyApp(ui = ui, server = server)
